package io.gitee.kotle.android.mvvm

import android.content.res.Resources
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.widget.PopupWindow
import androidx.annotation.StyleRes
import io.gitee.kotle.android.mvvm.mvvminterface.IBaseMvvm
import io.gitee.kotle.android.utils.appCompatActivity
import java.lang.NullPointerException

/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2021/11/22 5:36 下午
 *
 */
abstract class MvvmPopupWindow : PopupWindow(), IBaseMvvm {
    override fun showAsDropDown(anchor: View?, xoff: Int, yoff: Int, gravity: Int) {
        contentView = onCreateView(anchor)
        super.showAsDropDown(anchor, xoff, yoff, gravity)
    }

    override fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int) {
        contentView = onCreateView(parent)
        super.showAtLocation(parent, gravity, x, y)
    }

    /**
     * 创建view
     */
    protected open fun onCreateView(anchor: View?): View? {
        if (anchor == null) {
            throw NullPointerException("anchor is null")
        }
        //点击外面popupWindow消失
        isOutsideTouchable = true
        //popupWindow获取焦点
        isFocusable = true
        //popupWindow设置背景图
        setBackgroundDrawable(ColorDrawable())
        val view = onHandleCreateMvvmViewType(LayoutInflater.from(anchor.context), null, null)
            ?: throw NullPointerException("create view is null")
        onViewCreated(view)
        return view
    }

    /**
     * view创建完毕
     */
    protected open fun onViewCreated(view: View) {
        onViewCreatedFinish(view.appCompatActivity, null, view.resources)
    }

    /**
     * 设置窗口动画
     */
    fun setWindowAnimations(@StyleRes resId: Int) {
        animationStyle = resId
    }

    override fun checkScreenPortrait(resources: Resources) {
    }
}